/*
 * $Id$
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.demo.upload;

import com.lantu.draw.svgimg.service.SVGImageService;
import com.lantu.draw.svgimg.vo.SVGPaintIconVO;
import com.mysql.jdbc.StringUtils;
import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

/**
 * 
 * 
@ParentPackage("base")  
@Namespace("/watson")  
@Results({  
    @Result(name = "json",type="json", params={"root","msg"})  
})
 * Show case File Upload example's action. <code>FileUploadAction</code>
 */
public class FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = 5156288255337069381L;
	private static final Logger logger = Logger.getLogger(FileUploadAction.class);
	private String contentType;
	private File upload;
	private String fileName;
	private String caption;
	private String imgRepositoryPath;
	@Resource
	SVGImageService svgimgservice;
	public SVGImageService getSvgimgservice() {
		return svgimgservice;
	}
	public void setSvgimgservice(SVGImageService svgimgservice) {
		this.svgimgservice = svgimgservice;
	}
	public String getImgRepositoryPath() {
		return imgRepositoryPath;
	}
	public void setImgRepositoryPath(String imgRepositoryPath) {
		this.imgRepositoryPath = imgRepositoryPath;
	}
	public String input() throws Exception {
		return SUCCESS;
	}
	private static String getExtention(String fileName) {  
        int pos = fileName.lastIndexOf(".");  
        return fileName.substring(pos);  
    } 

    private Map<String, Object> msg;  
  
    public Map<String, Object> getMsg() {  
        return msg;  
    }  
	
	
	public String upload() throws Exception{
			logger.info(ServletActionContext.getRequest().getMethod());
			if(ServletActionContext.getRequest().getMethod().equals("OPTIONS")){
				ServletActionContext.getResponse().setHeader("Access-Control-Allow-Origin","*");
				ServletActionContext.getResponse().setHeader("Access-Control-Allow-Methods","POST");
				ServletActionContext.getResponse().setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
				msg = new HashMap<String, Object>(); 
				msg.put("code", "1");
				msg.put("desc", "成功");

				return SUCCESS;
			}
			// System.out.println(getFileContentType());
			// 读取文件内容到InputStream里
			InputStream is = new FileInputStream(upload);
			String imageFileName = new Date().getTime() + getExtention(fileName);  
			String usrHome = System.getProperty("user.home");
			imgRepositoryPath=usrHome;
			logger.info(imgRepositoryPath);
			String imgFilePath = imgRepositoryPath+"/repo/icon/"+imageFileName;
			//imgFilePath=ServletActionContext.getServletContext().getRealPath("/") + imageFileName;  
			logger.info(imgFilePath);
			// 创建输出流，生成新文件
			OutputStream os = new FileOutputStream(imgFilePath);
			// 将InputStream里的byte拷贝到OutputStream
			IOUtils.copy(is, os);
			os.flush();
			IOUtils.closeQuietly(is);
			IOUtils.closeQuietly(os);
			msg = new HashMap<String, Object>(); 
			msg.put("code", "1");
			msg.put("desc", "成功");
			SVGPaintIconVO vo=new SVGPaintIconVO();
			vo.setImgUrl(imgFilePath);
			HttpSession session=ServletActionContext.getRequest().getSession();
			vo.setUsrId((String)session.getAttribute("userid"));
			if(session.getAttribute("userid")==null||session.getAttribute("userid").equals("null")){//无用户登录情况下
				vo.setShared(true);
			}
			vo.setImgFileName(imageFileName);
			vo.setIp(ServletActionContext.getRequest().getRemoteAddr());
			svgimgservice.saveIcon(vo);
			return SUCCESS;
	}
	public String toUploadPage() throws Exception {
		return INPUT;
	}

	// since we are using <s:file name="upload" .../> the file name will be
	// obtained through getter/setter of <file-tag-name>FileName
	public String getUploadFileName() {
		return fileName;
	}

	public void setUploadFileName(String fileName) {
		this.fileName = fileName;
	}


	// since we are using <s:file name="upload" ... /> the content type will be
	// obtained through getter/setter of <file-tag-name>ContentType
	public String getUploadContentType() {
		return contentType;
	}

	public void setUploadContentType(String contentType) {
		this.contentType = contentType;
	}


	// since we are using <s:file name="upload" ... /> the File itself will be
	// obtained through getter/setter of <file-tag-name>
	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}


	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}
}
